<#include "../include/header.html">
<script type="text/javascript">
    var p_headerId = '${RequestParameters.headerId!0}';
    var viewModel = kendo.observable({
        model:{},
        create: function(){
            getLineNum();
        },


        saveHead: function () {
            savaOrderH();
        },
        close: function(){
            closeWin();
        },
        save: function(){
            saveLine();
        },
        remove: function () {
            Hap.deleteGridSelection({
                grid: $('#grid')
            });
        },
        deleteAll: function(){
            delete_headAndLine();
        },
        printPDF: function () {
            printPDF();
        }
    });

    if(p_headerId === '0' || p_headerId === null || p_headerId === undefined || p_headerId === '') {
        $.ajax({
            url:'${base.contextPath}/hap/om/order/lines/get_header',
            type:"POST",
            dataType:"json",
            contentType:"application/json",
            success:function(data){
                if(data.success == true){
                    viewModel.model.set("orderNumber",data.rows[0].orderNumber);
                    viewModel.model.set("orderDate",data.rows[0].orderDate);
                    viewModel.model.set("orderStatus",data.rows[0].orderStatus);
                }
            }
        });
    }else{
        Hap.loadViewModel({
            url:'${base.contextPath}/hap/om/order/headers/query?headerId='+p_headerId,
            model:viewModel.model
        });
    }

    /*<#if RequestParameters.headerId??>
    Hap.loadViewModel({
        url:'${base.contextPath}/hap/om/order/headers/query?headerId=${RequestParameters.headerId!0}',
        model:viewModel.model
    });
    </#if>*/
</script>
<body>
<script src="${base.contextPath}/common/code?HAP_OM_ORDER_STATUS=HAP_OM_ORDER_STATUS" type="text/javascript"></script>
<script src="${base.contextPath}/lib/bootstrap-3.3.7/js/bootstrap.min.js"></script>
<div id="page-content">
    <div class="panel" id="inQuery" style="padding: 0px;border:none;box-shadow: none;">
        <form class="form-horizontal" id="myForm">
            <div class="panel-body">

                <div class="row">

                    <div class="col-sm-4">
                        <div class="form-group">
                            <label class="col-sm-4 control-label"><@spring.message "OmOrderHeaders.orderNumber"/></label>
                            <div class="col-sm-8">
                                <input id='orderNumber' type="text" style="width: 100%" required data-label="<@spring.message 'OmOrderHeaders.orderNumber'/>"
                                       data-bind="value:model.orderNumber" disabled="true">
                            </div>
                        </div>
                    </div>

                    <div class="col-sm-4">
                        <div class="form-group">
                            <label class="col-sm-4 control-label"><@spring.message "OmOrderHeaders.companyId"/></label>
                            <div class="col-sm-8">
                                <input id='companyId' type="text" style="width: 100%" data-bind="value:model.companyId" required data-label="<@spring.message 'OmOrderHeaders.companyId'/>">
                                <script>
                                    $("#companyId").kendoLov($.extend(<@lov "LOV_ORG_COMPANY"/>, {
                                        textField: 'companyName',
                                        model: viewModel.model
                                    }));
                                </script>
                            </div>
                        </div>
                    </div>

                    <div class="col-sm-4">
                        <div class="form-group">
                            <label class="col-sm-4 control-label"><@spring.message "OmOrderHeaders.customerId"/></label>
                            <div class="col-sm-8">
                                <input id='customerId' type="text" style="width: 100%" data-bind="value:model.customerId">
                                <script>
                                    $("#customerId").kendoLov($.extend(<@lov "LOV_CUSTOMERS"/>, {
                                        //级联查询
                                        query: function (e) {
                                            e.param['companyId'] = $("#companyId").val();
                                        },
                                        textField: 'customerName',
                                        model: viewModel.model
                                    }));
                                </script>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">

                    <div class="col-sm-4">
                        <div class="form-group">
                            <label class="col-sm-4 control-label"><@spring.message "OmOrderHeaders.orderDate"/></label>
                            <div class="col-sm-8">
                                <input id='orderDate' type="text" style="width: 100%" data-bind="value:model.orderDate" data-role="datepicker" required data-label="<@spring.message 'OmOrderHeaders.orderDate'/>">
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-4">
                        <div class="form-group">
                            <label class="col-sm-4 control-label"><@spring.message "OmOrderHeaders.account_money"/></label>
                            <div class="col-sm-8">
                                <input id='account_money' type="text" style="width: 100%" data-bind="value:model.account_money" disabled="true">
                            </div>
                        </div>
                    </div>

                    <div class="col-sm-4">
                        <div class="form-group">
                            <label class="col-sm-4 control-label"><@spring.message "OmOrderHeaders.orderStatus"/></label>
                            <div class="col-sm-8">
                                <input id='orderStatus' type="text" style="width: 100%" data-bind="value:model.orderStatus" required data-label="<@spring.message 'OmOrderHeaders.orderStatus'/>">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="pull-left" id="query-form" style="padding-bottom:10px;">
                    <button id="saveHead" class="btn btn-primary" style="float:left;" data-bind="click:saveHead"
                            type="button"><i class="fa fa-save" style="margin-right: 3px;"></i> <@spring.message "hap.save"/></button>

                    <button id="submit" class="btn btn-primary" style="margin-left: 10px" onclick="submitApprove('SUBMITED')"
                            type="button"><i class="fa fa-eraser" style="margin-right:3px;"></i><@spring.message "hap.submit"/></button>

                    <button id="approve" class="btn btn-primary" style="margin-left: 10px" onclick="submitApprove('APPROVED')"
                                type="button"><i class="fa fa-eraser" style="margin-right:3px;"></i><@spring.message "hap.approve"/></button>

                    <button id="reject" class="btn btn-primary" style="margin-left: 10px" onclick="submitApprove('REJECTED')"
                                type="button"><i class="fa fa-eraser" style="margin-right:3px;"></i><@spring.message "hap.reject"/></button>


                    <button id="deleteAll" class="btn btn-primary" style="margin-left: 10px" data-bind="click:deleteAll"
                            type="button"><i class="fa fa-eraser" style="margin-right:3px;"></i><@spring.message "hap.delectAll"/></button>
                    <button id="print" class="btn btn-primary" style="margin-left: 10px" data-bind="click:printPDF"
                            type="button"><i class="fa fa-eraser" style="margin-right:3px;"></i><@spring.message "hap.printExcel"/></button>
                    <button id="close" class="btn btn-primary" style="margin-left: 10px" data-bind="click:close"
                            type="button"><i class="fa fa-eraser" style="margin-right:3px;"></i><@spring.message "hap.goBack"/></button>
                </div>
            </div>
        </form>

    </div>
    <div id="my_panel">
        <ul class="nav nav-tabs" id="mytab">
            <li class="active"><a href="#maintain" data-toggle="tab"><@spring.message "main.info"/></a></li>
            <li class=""><a href="#showTreeUnit" data-toggle="tab"><@spring.message "other.info"/></a></li>
        </ul>
        <div id="tabContent" class="tab-content">
            <div class="tab-pane fade in active" style="margin-top: 10px;" id="maintain">
                <div class="pull-left" id="toolbar-btn" style="padding-bottom:10px;">
                    <button id="mainCreate" class="btn btn-primary k-grid-add" style="float:left;margin-right:5px;" data-bind="click:create"><@spring.message "hap.new"/></button>
                    <button id="mainSave" class="btn btn-success k-grid-save-changes" data-bind="click:save" style="float:left;margin-right:5px;"><@spring.message "hap.save"/></button>
                    <button id="mainDelete" data-bind="click:remove" class="btn btn-danger" style="float:left;"><@spring.message "hap.delete"/>
                </div>
                <script>kendo.bind($('#toolbar-btn'), viewModel);</script>

                <div style="clear:both">
                    <div id="grid"></div>
                </div>
            </div>
            <div id="showTreeUnit" class="tab-pane fade">
                <div class="tab-pane fade in active" style="margin-top: 10px;">
                    <div class="pull-left" id="toolbar-btn1" style="padding-bottom:10px;">
                        <button type="button" class="btn btn-primary k-grid-add" style="float:left;margin-right:5px;" data-bind="click:create"><@spring.message "hap.new"/></button>
                        <button type="button" class="btn btn-success k-grid-save-changes" data-bind="click:save" style="float:left;margin-right:5px;"><@spring.message "hap.save"/></button>
                        <button type="button" onclick="deleteData()" class="btn btn-danger" style="float:left;"><@spring.message "hap.delete"/></button>
                    </div>
                </div>
                <script>kendo.bind($('#toolbar-btn1'), viewModel);</script>
                <div style="clear:both">
                    <div id="treeGrid" ></div>
                </div>
            </div>
        </div>
    </div>



<script type="text/javascript">

    kendo.bind($('#myForm'), viewModel);
    //定义校验器
    var validator = $("#myForm").kendoValidator({
        invalidMessageType : "tooltip"
    }).data("kendoValidator");

    var BaseUrl = _basePath;
    dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: BaseUrl + "/hap/om/order/lines/query",
                type: "POST",
                dataType: "json"
            },
            update: {
                url: BaseUrl + "/hap/om/order/lines/submit",
                type: "POST",
                contentType: "application/json"
            },
            destroy: {
                url: BaseUrl + "/hap/om/order/lines/remove",
                type: "POST",
                contentType: "application/json"
            },
            create: {
                url: BaseUrl + "/hap/om/order/lines/submit",
                type: "POST",
                contentType: "application/json"
            },
            parameterMap: function (options, type) {
                if (type !== "read" && options.models) {
                    var datas = Hap.prepareSubmitParameter(options, type)
                    return kendo.stringify(datas);
                } else if (type === "read") {
                    if(options.headerId) {
                        p_headerId = options.headerId;
                    }
                    var param1={};
                    param1["headerId"]=p_headerId;
                    return  Hap.prepareQueryParameter(param1, options);
                    //return Hap.prepareQueryParameter(viewModel.model.toJSON(), options)
                }
            }
        },
        batch: true,
        serverPaging: true,
        pageSize: 10,
        schema: {
            data: 'rows',
            total: 'total',
            model: {
                id: "lineId",
                fields: {
                    lineNumber:{

                    },
                    inventoryItemId:{
                        validation:{
                                required:true
                        }
                    },
                    itemDescription:{
                        validation:{
                            required:true
                        }
                    },
                    itemUom:{
                        validation:{
                            required: true
                        }
                    },
                    orderdQuantity:{
                        editable: true,
                        type: "string",
                        validation:{
                            required: true,
                            orderdQuantityValidation:function(input){
                                console.log(input.val)
                                if(input.val().substring(0,1) === '-'){
                                    kendo.ui.showInfoDialog({
                                        message: "数量不能小于0"
                                    });
                                    return false;
                                }
                                //数字区间的表达式
                                var regx = new RegExp("^[0-9]*$");
                                if(!regx.test(input.val())){
                                    kendo.ui.showInfoDialog({
                                        message: "请输入数字"
                                    });
                                    return false;
                                }
                                return true;
                            }
                        }
                    },
                    unitSellingPrice:{
                        validation:{
                            required: true,
                            orderUnitSellingPrice:function(input){
                                if(input.val().substring(0,1) === '-') {
                                    kendo.ui.showInfoDialog({
                                        message: "数量不能小于0"
                                    });
                                    return false;
                                }
                                var Regx = new RegExp("^[0-9]*$");
                                if(!Regx.test(input.val())) {
                                    kendo.ui.showInfoDialog({
                                        message: "请输入数字"
                                    });
                                    return false;
                                }
                                return true;
                            }
                        }
                    },
                    amount:{

                    },
                    description:{
                        validation:{
                            required: true
                        }
                    }
                },
                editable:function(col){
                    if(col=='lineNumber'){
                        return false;
                    }
                    if(col=='amount'){
                        return false;
                    }
                    return true;
                }

            }
        }
    });

    var orderGrid = $("#grid").kendoGrid({
        dataSource: dataSource,
        resizable: true,
        scrollable: true,
        navigatable: false,
        selectable: 'multiple, rowbox',
        dataBound: function () {
            if (parent.autoResizeIframe) {
                parent.autoResizeIframe('${RequestParameters.functionCode!}')
            }
        },
        pageable: {
            pageSizes: [5, 10, 20, 50],
            refresh: true,
            buttonCount: 5
        },
        columns: [

                    {
                field: "lineNumber",
                title: '<@spring.message "omorderlines.linenumber"/>',
                width: 50
            },
                    {
                field: "inventoryItemId",
                title: '<@spring.message "omorderlines.inventoryitemid"/>',
                width: 120,
                template:function(dataItem){
                    return dataItem['itemCode'] || ''
                },
               editor:function(container,options){
                   $('<input name="' + options.field + '"/>')
                           .appendTo(container)
                           .kendoLov($.extend(<@lov "LOV_INV"/>, {
                       textField: 'itemCode',
                       model: options.model,
                       select: function(e) {
                           options.model.set('itemCode', e.item.itemCode);
                           options.model.set('itemDescription', e.item.itemDescription);
                           options.model.set('itemUom', e.item.itemUom);
                       },
                       change: function(e) {
                           if (e.sender._prev == '' || e.sender._prev == null) {
                               options.model.set('itemCode', '');
                               options.model.set('itemDescription', '');
                               options.model.set('itemUom', '');
                           }
                       }
                   }));
               }
            },

            {
                field: "itemDescription",
                title: '<@spring.message "OmOrderLines.itemDescription"/>',
                width: 120,
                editor: function(container, options){
                    container.html(options.model.itemDescription);
                    container.removeClass('k-edit-cell');
                }
            },
            {
                field: "itemUom",
                title: '<@spring.message "OmOrderLines.itemUom"/>',
                width: 120,
                editor: function(container, options){
                    container.html(options.model.itemUom);
                    container.removeClass('k-edit-cell');
                }
            },
            {
                field: "orderdQuantity",
                title: '<@spring.message "omorderlines.orderdquantity"/>',
                width: 120
            },
            {
                field: "unitSellingPrice",
                title: '<@spring.message "OmOrderLines.unitSellingPrice"/>',
                width: 120
            },
            {
                field: "amount",
                    title: '<@spring.message "OmOrderLines.amount"/>',
                width: 120
            },
            {
                field: "description",
                title: '<@spring.message "omorderlines.description"/>',
                width: 120
            },

        ],
        editable: true
    });

    var treeGrid = $("#treeGrid").kendoGrid({
        dataSource: dataSource,
        resizable: true,
        scrollable: true,
        navigatable: false,
        selectable: 'multiple, rowbox',
        //autoBind:<#if RequestParameters.headerId??> true <#else> false</#if>,
        dataBound: function () {
            if (parent.autoResizeIframe) {
                parent.autoResizeIframe('${RequestParameters.functionCode!}')
            }
        },
        pageable: {
            pageSizes: [5, 10, 20, 50],
            refresh: true,
            buttonCount: 5
        },
        columns: [
            {
                field: "lineNumber",
                title: '<@spring.message "OmOrderLines.lineNumber"/>',
                width: 55,
            },
            {
                field: "addition1",
                title: '<@spring.message "OmOrderLines.addition1"/>',
                width: 120
            },
            {
                field: "addition2",
                title: '<@spring.message "OmOrderLines.addition2"/>',
                width: 120
            },
            {
                field: "addition3",
                title: '<@spring.message "OmOrderLines.addition3"/>',
                width: 120
            },
            {
                field: "addition4",
                title: '<@spring.message "OmOrderLines.addition4"/>',
                width: 120
            },
            {
                field: "addition5",
                title: '<@spring.message "OmOrderLines.addition5"/>',
                width: 120
            },

        ],
        editable: true
    });

    function submitApprove(status) {
        viewModel.model.orderStatus = status;
        Hap.submitForm({
            url: '${base.contextPath}/hap/om/order/headers/submit_head',
            formModel: viewModel.model,
            grid: {"omOrderLines": $("#grid")},
            success: function (data) {
                closeWin();
                window.parent.viewModel.refresh();
            }
        })
    }

    /*权限管理*/
    if($("#orderStatus").val() == 'NEW') {
        $("#approve").attr("disabled","true");
        $("#reject").attr("disabled","true");
    }
    if($("#orderStatus").val() == 'SUBMITED') {

        $("#saveHead").attr("disabled","true");
        $("#submit").attr("disabled","true");
        $("#deleteAll").attr("disabled","true");
        $("#mainCreate").attr("disabled","true");
        $("#mainSave").attr("disabled","true");
        $("#mainDelete").attr("disabled","true");

    }
    if($("#orderStatus").val() == 'APPROVED') {
        $("#saveHead").attr("disabled","true");
        $("#submit").attr("disabled","true");
        $("#approve").attr("disabled","true");
        $("#reject").attr("disabled","true");
        $("#deleteAll").attr("disabled","true");
        $("#mainCreate").attr("disabled","true");
        $("#mainSave").attr("disabled","true");
        $("#mainDelete").attr("disabled","true");

    }
    if($("#orderStatus").val() == 'REJECTED') {
        $("#approve").attr("disabled","true");
        $("#reject").attr("disabled","true");

    }


    //保存头表数据
    function savaOrderH(){
            if (validator.validate()) {
                Hap.submitForm({
                    url: '${base.contextPath}/hap/om/order/headers/submit_head',
                    formModel: viewModel.model,
                    grid: {"omOrderLines": $("#grid")},
                    success: function (data) {
                        kendo.ui.showInfoDialog({message:"操作成功"});
                    }
                });
            }


    }
    //保存行
    function saveLine(){

        if (validator.validate()) {
            Hap.submitForm({
                url: '${base.contextPath}/hap/om/order/headers/submit',
                formModel: viewModel.model,
                grid: {"omOrderLines": $("#grid")},
                success: function (data) {
                    $('#grid').data('kendoGrid').refresh();
                }
            });
        }
    }

    //打印单据
    function printPDF() {
        if (validator.validate()) {
            Hap.submitForm({
                url: '${base.contextPath}/hap/om/order/headers/printPDF',
                formModel: viewModel.model,
                grid: {"omOrderLines": $("#grid")},
                success: function (data) {
                    if(data.success==true){
                        window.location.href='${base.contextPath}/hap/om/order/headers/outputPDF';
                    }
                }
            });
        }
    }

    //整单删除
    function delete_headAndLine(){
        if (validator.validate()) {
            Hap.submitForm({
                url: '${base.contextPath}/hap/om/order/headers/deleteAll',
                formModel: viewModel.model,
                grid: {"omOrderLines": $("#grid")},
                success: function (data) {
                    window.parent.viewModel.refresh();
                    closeWin();
                }
            });
        }
    }

    //返回头页面
    function closeWin() {
        window.parent.viewModel.refresh();
        window.parent.$('#dialog').data("kendoWindow").close();
    }


    //获取行号
    function getLineNum(){

            $.ajax({
            url:'${base.contextPath}/hap/om/order/lines/get_row',
            type:"POST",
            dataType:"json",
            contentType:"application/json",
            success:function(args){
                if(args.success==true){

                    /*获取grid中的行数，包括新建的没数据的行*/
                    var len = orderGrid.data().handler.dataSource._data.length;
                    for(var i = 1; i <= len; i++) {
                        /*遍历grid中的所有行数据*/
                        var row = $('#grid').data('kendoGrid').dataItem("tr:eq(" + i +")");
                        row.lineNumber = i;
                        $('#grid').data('kendoGrid').refresh();
                        $('#treeGrid').data('kendoGrid').refresh();
                    }
                }
            }
        });

            $('#grid').data('kendoGrid').addRow();
    }

</script>
</body>
</html>